﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace KeyCount
{
    /// <summary>
    /// xml操作类
    /// </summary>
    public class XmlHelper
    {
        #region 变量
        private XmlDocument xmldoc = new XmlDocument();
        /// <summary>
        /// xml路径
        /// </summary>
        private string _xmlPath;
        /// <summary>
        /// xml路径
        /// </summary>
        public string XmlPath
        {
            get { return _xmlPath; }
            set { _xmlPath = value; }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 创建一个包含根节点xml文档
        /// <param name="xmlPath">文档路径</param>
        /// </summary>
        public void CreateXml()
        {
            //加入XML的声明段落
            xmldoc.AppendChild(xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null));
            //加入根元素
            XmlElement xmlelem = xmldoc.CreateElement("", "Root", "");
            XmlElement keysSumXM = xmldoc.CreateElement("KeysSum");//创建一个节点 
            keysSumXM.InnerText = "0";
            xmlelem.AppendChild(keysSumXM);
            XmlElement keyInfosXM = xmldoc.CreateElement("KeysInfos");
            xmlelem.AppendChild(keyInfosXM);
            xmldoc.AppendChild(xmlelem);
            try
            {
                if (File.Exists(_xmlPath))
                {
                    throw new ApplicationException("此文件已经存在！");
                }
                xmldoc.Save(_xmlPath);
            }
            catch (Exception e)    //捕获创建xml文件异常的
            {
                //显示错误信息
                throw new Exception("创建xml文件失败！\r原因：" + e.Message);
            }
        }
        /// <summary>
        /// 在指定的根节点下创建一个节点
        /// </summary>
        /// <param name="rootElementName">根节点名称</param>
        /// <param name="elementName"></param>
        public void CreateXmlElement(string rootElementName, string elementName)
        {
            xmldoc.Load(_xmlPath);
            XmlNode xn = xmldoc.SelectSingleNode("Root");//查找 

            XmlElement xe = xmldoc.CreateElement(elementName);//创建一个节点
            xn.AppendChild(xe);//添加到节点中 

            xmldoc.Save(_xmlPath);
        }
        /// <summary>
        /// 查找节点，并更新InnerText
        /// </summary>
        /// <param name="elementName">节点名称</param>
        /// <param name="value">值</param>
        public void UpdataXmlElement(string elementName, string value)
        {
            XmlNodeList nodeList = xmldoc.SelectSingleNode("Root").ChildNodes;//;//获取根节点的所有子节点 
            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    XmlElement xe = (XmlElement)node;//转换类型 
                    if (xe.Name == elementName)
                    {
                        xe.InnerText = value;    //修改
                        break;
                    }
                    else
                    {
                        UpdataChildXmlElement(xe.Name, value);
                    }
                }
            }
            else
            {
                return;
            }
            xmldoc.Save(_xmlPath);//保存。
        }
        private void UpdataChildXmlElement(string elementName, string value)
        {
            try
            {
                XmlNodeList nodeList = xmldoc.SelectSingleNode(elementName).ChildNodes;
                if (nodeList != null)
                {
                    foreach (XmlNode nd in nodeList)
                    {
                        XmlElement xe = (XmlElement)nd;//转换类型 
                        if (xe.Name == elementName)
                        {
                            xe.InnerText = value;    //修改
                            break;
                        }
                        else
                        {
                            UpdataChildXmlElement(xe.Name, value);
                        }
                    }
                }
                else
                {
                    return;
                }
                xmldoc.Save(_xmlPath);//保存。
            }
            catch (NullReferenceException)
            {
                return;
            }
        }
        /// <summary>
        /// 检查节点是否存在。
        /// </summary>
        /// <param name="elementName">节点名称</param>
        /// <returns>存在=true;不存在=false</returns>
        public bool ExistsXmlElement(string elementName)
        {
            xmldoc.Load(_xmlPath);
            XmlNodeList rootList = xmldoc.SelectSingleNode("Root").ChildNodes;//查找节点
            if (rootList != null)
                foreach (XmlNode xn in rootList)
                {
                    if (xn.Name == elementName)
                    {
                        return true;
                    }
                }
            return false;
        }
        public string ReadXmlElement(string xmlElementName)
        {
            xmldoc.Load(_xmlPath);
            XmlNodeList xnList = xmldoc.SelectSingleNode("Root").ChildNodes;
            if (xnList != null && xnList.Count > 0)
            {
                foreach (XmlNode xn in xnList)
                {
                    XmlElement xe = (XmlElement)xn;
                    if (xe.Name == xmlElementName)
                    {
                        return xe.InnerText;
                    }
                }
            }
            return "";
        }
        #endregion
    }
}
